package com.share.gateway.filter;

import com.share.constant.SecurityConstant;
import com.share.gateway.utils.TokenUtils;
import com.share.properties.GatewayWhitelist;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    private final GatewayWhitelist whitelist;
    private final TokenUtils tokenUtils;

    @Autowired
    public AuthorizeFilter(GatewayWhitelist whitelist, TokenUtils tokenUtils) {
        this.whitelist = whitelist;
        this.tokenUtils = tokenUtils;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("进入 AuthorizeFilter，请求路径: {}", exchange.getRequest().getURI().getPath());
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String requestURI = request.getURI().getPath();

        // 1. 检查是否在白名单
        if (isWhitelisted(requestURI)) {
            log.debug("放行白名单请求: {}", requestURI);
            return chain.filter(exchange);
        }

        // 2. 获取 Token
        String token = extractToken(request);

        // 3. 验证 Token
        if (!validateToken(token, response)) {
            return response.setComplete();
        }

        // 4. 放行（携带 Token）
        return chain.filter(exchange);
    }

    /**
     * 检查请求是否在白名单
     */
    private boolean isWhitelisted(String requestURI) {
        // 排除 actuator 等管理端点
        if (requestURI.startsWith("/actuator")) {
            return true;
        }
        return whitelist.getExcludeList().stream()
                .anyMatch(path -> pathMatcher.match(path, requestURI));
    }

    /**
     * 从 Header 提取 Token
     */
    private String extractToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(SecurityConstant.AUTHORIZATION_KEY);
        if (StringUtils.isBlank(token)) {
            throw new RuntimeException();
        }
        if (token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        return token;
    }

    /**
     * 验证 Token 是否有效
     */
    private boolean validateToken(String token, ServerHttpResponse response) {
        try {
            if (tokenUtils.isTokenExpired(token)) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("Token 验证失败", e);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public int getOrder() {
        return 1; // 优先级最高
    }
}